package com.stars.common.jwt;

import com.stars.common.signature.RsaUtil;
import com.stars.common.signature.TernaryUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author : alex
 * @version ：1.0.0
 * @Date : create by 2017/11/9 19:44
 * @description ：JWT工具类,用于加密和解析
 * @note 注意事项
 */
public class JWTUtil {

    private  final Logger logger = LoggerFactory.getLogger(JWTUtil.class);

    private static String JwtUserId = "userId"; //只是命名，如同map里的key,可以通过此参数获取其存储的属性
    private static String JwtName = "name";     //只是命名，如同map里的key,可以通过此参数获取其存储的属性


    /**
     * 密钥加密token
     * @param info  用户主体类
     * @param expireTime    设置过期时间
     * @param priPath   私钥路径
     * @return
     * @throws Exception
     */
    public static String generateToken(JWTInfo info,Integer expireTime,String priPath) throws Exception {
        String compactJws = Jwts.builder()
                .setSubject(info.getUsername())
                .claim(JwtUserId,info.getUserId())
                .claim(JwtName,info.getName())
                .setExpiration(DateTime.now().plusSeconds(expireTime).toDate())//设置过期时间
                .signWith(SignatureAlgorithm.RS256, RsaUtil.getPrivateKey(priPath))
                .compact();
        return compactJws;
    }

    /**
     * 公钥解析token
     * @param token
     * @param pubPath 公钥路径
     * @return
     * @throws Exception
     */
    public static Jws<Claims> parserToken(String token, String pubPath) throws Exception {
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(RsaUtil.getPublicKey(pubPath)).parseClaimsJws(token);
        return claimsJws;
    }


    /**
     * 获取token中的用户信息
     * @param token token
     * @param pubPath   公钥路径
     * @return
     * @throws Exception
     */
    public static JWTInfo getInfoFromToken(String token,String pubPath) throws Exception {
        Jws<Claims> claimsJws = parserToken(token,pubPath);
        Claims body = claimsJws.getBody();
        return new JWTInfo(body.getSubject(), TernaryUtil.getString(body.get(JwtUserId)), TernaryUtil.getString(body.get(JwtName)));
    }
}
